from django.contrib import auth
from django.shortcuts import render,redirect
from django.core.paginator import Paginator

from .models import *

# Create your views here.

#登录
def login(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            auth.login(request, user)
            return redirect('/index/')
        else:
            return render(request, 'login.html', {"error": "错误"})
    return render(request, 'login.html')

#展示，搜索，分页
def index(request):
    title=request.GET.get("title",'')#根据标题搜索
    if title is not None:
        title=Book.objects.filter(title__contains=title)#模糊查询
    else:
        title=Book.objects.all()
    paginator=Paginator(title,2)#分页，两条数据分一页
    x = request.GET.get("page", '1')
    try:
        x = int(x)
        if x < 0:
            x = 1
    except Exception as e:
        x = 1
    pagex = paginator.get_page(x)
    return render(request,'index.html',{"pagex":pagex,"hasnext":pagex.has_next(),"title":title})

#删除
def book_del(request,id):
    b_del=Book.objects.get(id=id)
    b_del.delete()
    return redirect('index')


#展示作者对应的标题
def user_info(request):
    userid = request.GET.get("userid", "")
    author = User.objects.filter(user_id=userid)
    return render(request, 'author.html', {"author": author})